<template>
  <div class="content-release section-container">
    <div class="content-list">
      <div class="section-title">
        我的发布
      </div>
      <el-tabs v-model="curState" @tab-change="handleTabChange">
        <el-tab-pane v-for="item in tabArr" :key="item.state" :label="item.name" :name="item.state" />
      </el-tabs>
      <div class="section-actions">
        <div class="actions-left">
          <SearchCmp ref="searchCmpRef" v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="handleSearch" />
        </div>
      </div>
      <!-- 表格样式 -->
      <div class="ruifox-list">
        <RuifoxTable
          :key="curState"
          :loading="tableLoading"
          v-model:tableData="tableData"
          v-model:fieldList="fieldList"
          :default-index="true"
          :tableProps="tableProps"
          @handleSearch="handleSearch"
        >
          <!-- 置顶 -->
          <template #is_top="{ element }">
            <div class="table-td-top unmover">
              <span :class="{ 'ding-yes': element.is_top, 'ding-no': !element.is_top }" @click="handleTop(element)">顶</span>
            </div>
          </template>
          <!-- 锁定 -->
          <template #is_lock="{ element }">
            <el-tag type="danger" v-if="element.is_lock">已锁定</el-tag>
            <el-tag type="success" v-else>未锁定</el-tag>
          </template>
          <!-- 创建时间 -->
          <template #create_time="{ element }">
            {{ dayjs(element.create_time).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <!-- 操作 -->
          <template #options="{ element }">
            <div class="table-td-option">
              <el-button
                v-if="hasPermission(['content:manage:setting:edit']) && [99, 1, 3].includes(curState)"
                type="primary"
                link
                @click="handleEdit(element)"
                :disabled="!element.is_lock ? false : true"
              >
                编辑
              </el-button>
              <el-button type="primary" link v-if="hasPermission(['content:manage:setting:preview'])" @click="handleViewFront(element)">前台浏览</el-button>
              <el-dropdown>
                <span class="el-dropdown-link unmover">
                  <i class="iconfont">&#xe78d;</i>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-if="hasPermission(['content:manage:revoke']) && [99].includes(curState)" @click="handleRevoke(element)" :disabled="!element.is_lock ? false : true">撤稿</el-dropdown-item>
                    <el-dropdown-item v-if="hasPermission(['content:manage:top']) && [99, 0, 1, 2, 3, 4].includes(curState)" @click="handleTop(element)">
                      {{ element.is_top ? '取消置顶' : '置顶' }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </RuifoxTable>
      </div>
      <PaginationView
        :total="queryData.total"
        :pageSize="queryData.pageSize"
        :currentPage="queryData.currentPage"
        :allChoose="isAllChooseBtn"
        :pageChoose="isPageChooseBtn"
        :checkedNum="checkedNum"
        :canChoose="false"
        @changeSize="handleSizeChange"
        @currentChange="handleCurrentChange"
        @changePageChoose="handlePageChoose"
        @changeAllChoose="handleAllChoose"
        @cancelChoose="handleResetPagination"
        @invertChoose="handleInvertChoose"
        @refreshList="getTableData"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateSystemData, getMyPublish } from '@/api/referenceData'
import { getModelByCatId } from '@/api/model'
import { tableList as mixTable, hasPermission } from '@ruifox-cms/utils'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'

const router = useRouter()
// 分页逻辑局部混入
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  getTableData,
  handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleResetPagination
} = mixTable({
  getListApi: getMyPublish
})

// 顶部tab及各状态可操作选项（注意添加state不要重复）
const curState = ref(99)
if (router.currentRoute.value.query.state) {
  curState.value = Number(router.currentRoute.value.query.state)
}
const tabArr = reactive([
  {
    state: 99,
    name: '已发布'
  },
  {
    state: 5,
    name: '待发布'
  },
  {
    state: 0,
    name: '审核中'
  },
  {
    state: 2,
    name: '撤稿箱'
  },
  {
    state: 3,
    name: '已退稿'
  },
  {
    state: 4,
    name: '已归档'
  }
])
const searchCmpRef = ref(null)
const handleTabChange = () => {
  searchCmpRef.value.clearForm(queryData)
  searchCmpRef.value.showTags()
  queryData.state = curState.value
  handleResetPagination()
  getTableData()
}

// 表头数据处理
const fieldList = ref([
{
    name: '置顶',
    field: 'is_top',
    width: 30,
    hideTitle: true,
    fixed: 'left'
  },
  {
    name: '标题',
    field: 'title',
    width: 450,
    fixed: 'left',
    showTextTip: true
  },
  {
    name: '所在栏目',
    field: 'category_name'
  },
  {
    name: '创建时间',
    field: 'create_time'
  },
  {
    name: '操作',
    field: 'options',
    width: 150,
    fixed: 'right'
  }
])
const tableProps = reactive({
  labelKey: 'name',
  valueKey: 'field'
})
const searchCmpArray = ref([{ label: '标题', key: 'title' }])
// 内容列表查询参数
const defaultQueryData = reactive({
  currentPage: 1,
  pageSize: 10,
  state: router.currentRoute.value.query.state || 99
})
Object.assign(queryData, defaultQueryData)
/*************************************************************行操作*************************************/
// 编辑内容
const handleEdit = async data => {
  const res = await getModelByCatId({ catId: data.cat_id })
  if (res.code !== 20000) {
    ElMessage.error('获取模型失败，无法预览')
    return
  }
  const toUrl = router.resolve({
    path: '/content2/list/setting',
    query: {
      modelId: res.data.id,
      publishType: res.data.publishType,
      catId: data.cat_id,
      dataId: data.state === 1 ? null : data.data_id,
      draftId: data.state === 1 ? data.data_id : null,
      isReject: data.state === 3 ? true : null
    }
  })
  window.open(toUrl.href, '_blank')
}

// 撤稿
const handleRevoke = data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除该内容？</p><span style="font-size: 14px;color: #FF5240;">清除后内容将无法恢复</span></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    const obj = {
      catId: data.cat_id,
      id: data.id,
      state: 2
    }
    updateSystemData(obj).then(res => {
      if (res.code === 20000) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      getTableData()
    })
  })
}

// 置顶取消置顶
const handleTop = data => {
  const obj = {
    catId: data.cat_id,
    ids: [data.id],
    isTop: data.is_top ? false : true,
    isAllChoose: false,
    params: null
  }
  updateSystemData(obj).then(res => {
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: data.isTop ? '取消置顶成功' : '置顶成功',
        type: 'success'
      })
    }
    getTableData()
  })
}

// 前台浏览
const handleViewFront = data => {
  if (data.url) {
    // 已发布就直接访问前台地址
    window.open(data.url, '_blank')
  } else {
    // 无url提示无法预览
    ElMessage.warning('无法预览')
  }
}

onMounted(() => {
  getTableData()
})
</script>

<style lang="scss" scoped>
.content-release {
  flex: 1;

  .content-list {
    width: 100%;
    .ruifox-card-options {
      .ruifox-card-btn {
        i {
          margin-right: 5px;
        }
      }
    }
    .ruifox-list {
      .collect-btn i {
        color: #ccc;
        cursor: pointer;
      }
      .collect-btn.is-collect i {
        color: $mainColor;
      }
      .table-td-top {
        width: 18px;
        min-width: 18px;
        .ding-yes {
          display: inline-block;
          width: 16px;
          height: 16px;
          font-size: 12px;
          color: $white;
          line-height: 16px;
          text-align: center;
          background-color: #ff5240;
          cursor: pointer;
          margin-right: 5px;
        }
        .ding-yes:hover {
          background-color: #f78a7e;
        }
        .ding-no {
          display: inline-block;
          cursor: pointer;
          width: 16px;
          height: 16px;
          font-size: 12px;
          color: $white;
          line-height: 16px;
          text-align: center;
          background-color: #d7d7d7;
          margin-right: 5px;
          visibility: hidden;
        }
        .ding-no:hover {
          background-color: #817f7f;
        }
      }
      .table-td-title {
        display: flex;
        align-items: center;
        .title-tips {
          .iconfont {
            font-size: 14px;
            color: $mainColor;
            margin-right: 3px;
          }
          span {
            color: #aaa;
            margin-right: 20px;
            position: relative;
          }
          span + span:before {
            content: '|';
            position: absolute;
            left: -10px;
            top: -8px;
          }
        }
        .title-box {
          display: flex;
          justify-content: center;
          align-items: center;
          p {
            @include textEllipsis(16px, 1);
          }
          .iconimg {
            display: inline-block;
            width: 16px;
            margin-right: 5px;
            i {
              color: #2cbf77;
              font-size: 15px;
            }
          }
          .a-icon {
            display: inline-block;
            width: 16px;
            background-color: $mainColor;
            color: $white;
            line-height: 16px;
            text-align: center;
            i {
              font-size: 14px;
            }
          }
          .p-icon {
            display: flex;
            align-items: center;
            width: 20px;
            color: #2cbf77;
            i {
              font-size: 18px;
            }
          }
          .thumb-box {
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }
  .button-box {
    padding-right: 10px;
    .el-button + .el-button {
      margin-left: 0;
    }
    flex-grow: 0;
    position: relative;
    i {
      position: absolute;
      right: -13px;
      top: 5px;
      color: $mainColor;
      cursor: pointer;
    }
  }
  .libarary-table {
    width: 100%;
    ::v-deep(.el-table__cell) {
      height: 50px;
      padding: 4px 0;
    }
    .option-btn {
      width: 35px;
    }
  }
}
</style>
